package com.example.javaee.service.impl;

import com.example.javaee.Util.sensitiveWordFilter.SensitiveFilter;
import com.example.javaee.dao.CommentMapper;
import com.example.javaee.dao.CourseMapper;
import com.example.javaee.dao.UserDislikeMapper;
import com.example.javaee.dao.UserLikeMapper;
import com.example.javaee.domain.Comment;
import com.example.javaee.domain.UserDislike;
import com.example.javaee.domain.UserLike;
import com.example.javaee.exception.CourseAdminException;
import com.example.javaee.service.CommentService;

import com.example.javaee.service.CourseService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    CourseService courseService;

    @Autowired
    SensitiveFilter sensitiveFilter;

    @Autowired
    UserLikeMapper userLikeMapper;

    @Autowired
    UserDislikeMapper userDislikeMapper;

    @Autowired
    ImageService imageService;


    Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

    //存放迭代找出的所有子代的集合
    private List<Comment> tempReplys = new ArrayList<>();

    @Override
    public List<Comment> findBycourseNumber(Long courseNumber) throws CourseAdminException, IOException {

        List<Comment> comments = commentMapper.findByParentIdNull(Long.parseLong("-1"),courseNumber);


        for(Comment comment : comments){
            Long id = comment.getId();
            comment.setReplyComments(commentMapper.findByCourseCommentId(id));
            for(Comment subComment : comment.getReplyComments())
            {
                setCommentAvatar(subComment);
            }
            setCommentAvatar(comment);
        }
        return comments;
    }

    //按userid查询其所有评论
    public List<Comment> findByUserId(@Param("userId") Integer userId){
        List<Comment> comments=commentMapper.findByUserId(userId);
        for(Comment comment : comments){
            comment.setCourseName(courseService.getCourseName(comment.getCourseNumber()));
        }
        return comments;
    }

    /**
     * @Description: 查询评论
     * @Param:
     * @Return: 评论消息
     */
    @Override
    public List<Comment> listComment() throws CourseAdminException
    {

        return null;
    }

    /**
     * @Description: 查询出子评论
     * @Param: childComments：所有子评论
     * @Param: parentNickname1：父评论的姓名
     * @Return:
     */
    private void combineChildren(List<Comment> childComments, String parentNickname1) throws CourseAdminException
    {
        //判断是否有一级子回复
        if(childComments.size() > 0){
            //循环找出子评论的id
            for(Comment childComment : childComments){
                String parentNickname = childComment.getNickname();
                childComment.setParentNickname(parentNickname1);
                tempReplys.add(childComment);
                Long childId = childComment.getId();
                //查询二级以及所有子集回复
                recursively(childId, parentNickname);
            }
        }
    }

    /**
     * @Description: 循环迭代找出子集回复
     * @Param: childId：子评论的id
     * @Param: parentNickname1：子评论的姓名
     * @Return:
     */
    private void recursively(Long childId, String parentNickname1) throws CourseAdminException
    {
        //根据子一级评论的id找到子二级评论
        List<Comment> replayComments = commentMapper.findByReplayId(childId);

        if(replayComments.size() > 0){
            for(Comment replayComment : replayComments){
                String parentNickname = replayComment.getNickname();
                replayComment.setParentNickname(parentNickname1);
                Long replayId = replayComment.getId();
                tempReplys.add(replayComment);
                //循环迭代找出子集回复
                recursively(replayId,parentNickname);
            }
        }
    }

    @Override
    //存储评论信息
    public Comment saveComment(Comment comment)  throws CourseAdminException
    {
        if(comment.getParentCommentId() == null || comment.getCourseNumber() == null)
        {
            throw new CourseAdminException(
                    "添加评论失败，comment缺少parentCommentId或courseNumber!");
        }
        try
        {
            // 如果该评论为二级及以上评论，同步父评论的courseCommentId属性，方便以后查询
            if(comment.getParentCommentId() != -1)
            {
                //给comment添加@父评论的name
                String content = sensitiveFilter.filter(comment.getContent());
                Comment parentComment = commentMapper.findById((long) comment.getParentCommentId());
                comment.setContent(content+"@"+parentComment.getNickname());
                Long courseCommentId = parentComment.getCourseCommentId();
                comment.setCourseCommentId((courseCommentId == -1) ? parentComment.getId() : courseCommentId);
            }
            else
            {
                String content = sensitiveFilter.filter(comment.getContent());
                comment.setContent(content);
                comment.setCourseCommentId((long) -1);
            }
            // 屏蔽评论内容中的敏感词
            //String content = sensitiveFilter.filter(comment.getContent());
            //comment.setContent(content);
            comment.setCreateTime(new Date());
            comment.setLikeCount(0L);
            comment.setDislikeCount(0L);
            commentMapper.saveComment(comment);
            return comment;
        }
        catch (Exception e)
        {
            throw new CourseAdminException(
                    "添加评论失败!");
        }
    }
    @Override
    public void addLikeCount(Integer userId, Long commentId) throws CourseAdminException
    {
        if(userId == null || commentId == null)
        {
            throw new CourseAdminException(
                    "userId或者commentId未输入!");
        }
        Comment comment = commentMapper.findById(commentId);
        UserLike userLike = userLikeMapper.findByUserIdAndCommentId(userId, commentId);
        UserDislike userDislike = userDislikeMapper.findByUserIdAndCommentId(userId, commentId);
        if (comment == null)
        {
            throw new CourseAdminException(
                    "该评论不存在!");
        }
        if(userLike != null)
        {
            throw new CourseAdminException(
                    "点赞失败，您已经点过赞!");
        }
        if (userDislike != null)
        {
            userDislikeMapper.deleteByUserIdAndCommentId(userId, commentId);
            Long dislike = comment.getDislikeCount();
            dislike--;
            commentMapper.updateDislikeCount(comment.getId(), dislike);
        }
        try
        {
            Long like = comment.getLikeCount();
            like++;
            userLike = new UserLike(userId, commentId);
            userLikeMapper.insert(userLike);
            commentMapper.updateLikeCount(comment.getId(), like);
        }
        catch (Exception e)
        {
            throw new CourseAdminException(
                    "点赞失败!");
        }
    }
    @Override
    public void undoLike(Integer userId, Long commentId) throws CourseAdminException
    {
        try
        {
            Comment comment = commentMapper.findById(commentId);
            Long like = comment.getLikeCount();
            like--;
            commentMapper.updateLikeCount(comment.getId(), like);
            userLikeMapper.deleteByUserIdAndCommentId(userId, commentId);
        }
        catch (Exception e)
        {
            throw new CourseAdminException(
                    "撤销点赞失败!");
        }
    }

    @Override
    public void addDislikeCount(Integer userId, Long commentId) throws CourseAdminException
    {
        if(userId == null || commentId == null)
        {
            throw new CourseAdminException(
                    "userId或者commentId未输入!");
        }
        Comment comment = commentMapper.findById(commentId);
        UserLike userLike = userLikeMapper.findByUserIdAndCommentId(userId, commentId);
        UserDislike userDislike = userDislikeMapper.findByUserIdAndCommentId(userId, commentId);        if (comment == null)
        {
            throw new CourseAdminException(
                    "该评论不存在!");
        }
        if(userDislike != null)
        {
            throw new CourseAdminException(
                    "点赞失败，您已经点过踩!");
        }
        if(userLike != null)
        {
            userLikeMapper.deleteByUserIdAndCommentId(userId, commentId);
            Long like = comment.getLikeCount();
            like--;
            commentMapper.updateLikeCount(comment.getId(), like);
        }
        try
        {
            Long dislike = comment.getDislikeCount();
            dislike++;
            userDislike = new UserDislike(userId, commentId);
            userDislikeMapper.insert(userDislike);
            commentMapper.updateDislikeCount(comment.getId(), dislike);
        }
        catch (Exception e)
        {
            throw new CourseAdminException(
                    "点赞失败!");
        }
    }

    @Override
    public void undoDislike(Integer userId, Long commentId) throws CourseAdminException
    {
        try
        {
            Comment comment = commentMapper.findById(commentId);
            Long dislike = comment.getDislikeCount();
            dislike--;
            commentMapper.updateDislikeCount(comment.getId(), dislike);
            userDislikeMapper.deleteByUserIdAndCommentId(userId, commentId);
        }
        catch (Exception e)
        {
            throw new CourseAdminException(
                    "撤销点踩失败!");
        }
    }

    @Override
    @Transactional
    public void deleteComment(Long id) // throws CourseAdminException
    {
        Comment comment = commentMapper.findById(id);
        if(comment.getCourseCommentId() == -1)
        {
            commentMapper.deleteSubComments(comment.getId());
        }
        commentMapper.deleteById(comment.getId());
    }

    public void setCommentAvatar(Comment comment) throws IOException
    {
        String headerStr = imageService.getHeaderString(comment.getUserId());
        if(headerStr == "")
        {
            return ;
        }
        comment.setAvatar("data:image/png;base64," + headerStr);
    }

    @Override
    public List<Comment> adminFindByCourseNumber(Long courseNumber){
        List<Comment> result = new ArrayList<>();
        result = commentMapper.adminFindByCourseNumber(courseNumber);
        return result;
    }
}
